package com.haohan.cloud.scm.saleb.core.impl;

import cn.hutool.core.util.StrUtil;
import com.haohan.cloud.scm.api.constant.enums.saleb.BuyOrderStatusEnum;
import com.haohan.cloud.scm.api.saleb.entity.BuyOrderDetail;
import com.haohan.cloud.scm.saleb.core.BuyOrderDetailCoreService;
import com.haohan.cloud.scm.saleb.service.BuyOrderDetailService;
import com.pig4cloud.pigx.common.core.util.R;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * @author dy
 * @date 2019/9/17
 */
@Service
@AllArgsConstructor
public class BuyOrderDetailCoreServiceImpl implements BuyOrderDetailCoreService {

    private final BuyOrderDetailService buyOrderDetailService;

    /**
     * 修改采购单明细采购价及采购数量
     * 采购数量 在 已下单/待确认 可修改
     * 采购价  不在 已成交/已取消 可修改
     *
     * @param buyOrderDetail buyDetailSn / buyPrice /goodsNum
     * @return
     */
    @Override
    public R<BuyOrderDetail> modifyDetail(BuyOrderDetail buyOrderDetail) {
        BuyOrderDetail detail = buyOrderDetailService.fetchBySn(buyOrderDetail.getBuyDetailSn());
        if (null == detail) {
            return R.failed("采购单明细有误");
        }
        BuyOrderDetail update = new BuyOrderDetail();
        update.setId(detail.getId());
        boolean flag = false;
        String msg = "";

        BuyOrderStatusEnum status = detail.getStatus();
        BigDecimal goodsNum = buyOrderDetail.getGoodsNum();
        // 状态
        boolean statusFlag = status == BuyOrderStatusEnum.submit || status == BuyOrderStatusEnum.wait;
        boolean numChange = null != goodsNum && goodsNum.compareTo(detail.getGoodsNum()) != 0;
        if (statusFlag && numChange) {
            update.setGoodsNum(goodsNum);
            update.setOrderGoodsNum(goodsNum);
            detail.setGoodsNum(goodsNum);
            detail.setOrderGoodsNum(goodsNum);
            flag = true;
            msg += "下单数量已修改,";
        }
        BigDecimal price = buyOrderDetail.getBuyPrice();
        statusFlag = !(status == BuyOrderStatusEnum.success || status == BuyOrderStatusEnum.cancel);
        numChange = null != price && price.compareTo(detail.getBuyPrice()) != 0;
        if (statusFlag && numChange) {
            update.setBuyPrice(price);
            detail.setBuyPrice(price);
            flag = true;
            msg += "采购价格已修改,";
        }
        if (!flag) {
            msg += "采购单明细下单数量和采购价格未修改,";
        }
        // 修改备注
        String remarks = buyOrderDetail.getRemarks();
        if (StrUtil.isNotBlank(remarks)) {
            update.setRemarks(remarks);
            detail.setRemarks(remarks);
            msg += "采购单明细备注已修改";
        }
        if (!buyOrderDetailService.updateById(update)) {
            return R.failed("采购单明细修改失败");
        }
        return R.ok(detail, msg);
    }
}
